﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KmSql.Shared;

namespace KmSql.SqlServer.Ado
{
    public class SqlServerAdo : IAdo
    {
        public string ConnectionString { get; init; }

        public SqlServerAdo(string connectionString)
        {
            ConnectionString = connectionString;
        }

        public async Task<DataTable> QueryAsync(string sql, SqlParameter[]? pars = null)
        {
            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                await con.OpenAsync();
                SqlDataAdapter sda = new SqlDataAdapter(sql, con);
                if (pars != null)
                    sda.SelectCommand.Parameters.AddRange(pars);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                return dt;
            }
        }

        public async Task<int> ExecuteNonQueryAsync(string sql, SqlParameter[]? pars = null)
        {
            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                await con.OpenAsync();
                SqlCommand com = new SqlCommand(sql, con);
                if (pars != null)
                    com.Parameters.AddRange(pars);
                int result = await com.ExecuteNonQueryAsync();
                return result;
            }
        }

        public async Task<object?> ExecuteScalarAsync(string sql, SqlParameter[]? pars = null)
        {
            var dt = await QueryAsync(sql, pars);
            return dt?.Rows[0]?[0];
        }

        public async Task<List<T>> QueryAsync<T>(string sql, SqlParameter[]? pars = null) where T : class
        {
            var dt = await QueryAsync(sql, pars);
            return dt.ToList<T>();
        }

        public async Task<T?> FirstAsync<T>(string sql, SqlParameter[]? pars = null) where T : class
        {
            var dt = await QueryAsync(sql, pars);
            return dt?.Rows[0]?.ToEntity<T>();
        }
    }
}
